//axios 基础的封装
//配置axios
import axios from 'axios'
import {useUserStore} from "@/stores/user";

// /********** 携带session ************/
axios.defaults.withCredentials = true; //保持sessionId不变
const userStore = useUserStore()
// 创建axios实例
const request = axios.create({
    withCredentials: true,
    baseURL: '/api',
    // 开发
    // baseURL:'/mock'
})

request.interceptors.response.use(
    response => {
        const {code, msg} = response.data;
        if (code === 200) {
            return response.data;
        }
        // 响应数据为二进制流处理(Excel导出)
        if (response.data instanceof ArrayBuffer) {
            return response;
        }
        /**
         *  10011 登陆失败
         */
        if (code === 401) {
            ElMessageBox.alert("当前页面已失效，请重新登录", "提示", {
                confirmButtonText: "确定",
                type: "warning",
            }).finally(() => {
                userStore.reset()
                window.location.href = "/login"
            });
        }else{
            console.log(msg,code)
            ElMessage.error(msg + code || "系统出错，请稍后再试")
            return Promise.reject(new Error(msg || "系统出错，请稍后再试"));
        }
    },
    //接口错误状态处理，也就是说无响应时的处理
    error => {
        return Promise.reject(error.message);//接口返回的错误信息
    }
)

export default request